<template>
  <a-layout-header class="header">
    <a-row :wrap="false">
      <!-- 左侧：Logo和标题 -->
      <a-col flex="200px">
        <RouterLink to="/">
          <div class="header-left">
            <img class="logo" src="@/assets/logo.svg" alt="Logo" />
            <h1 class="site-title">应用生成</h1>
          </div>
        </RouterLink>
      </a-col>
      <!-- 中间：导航菜单 -->
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="selectedKeys"
          mode="horizontal"
          :items="menuItems"
          @click="handleMenuClick"
          class="nav-menu"
        />
      </a-col>
      <!-- 右侧：用户操作区域 -->
      <a-col>
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser.id">
            <a-dropdown>
              <a-space class="user-name">
                <a-avatar :src="loginUserStore.loginUser.userAvatar" />
                {{ loginUserStore.loginUser.userName ?? '无名' }}
              </a-space>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="showUpdateModal">
                    <EditOutlined />
                    修改信息
                  </a-menu-item>
                  <a-menu-item @click="doLogout">
                    <LogoutOutlined />
                    退出登录
                  </a-menu-item>
                  <a-menu-item @click="showPasswordModal">
                    <LockOutlined />
                    修改密码
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>

          <div v-else>
            <a-button type="primary" href="/user/login" class="login-button">登录</a-button>
          </div>
        </div>
      </a-col>
    </a-row>
  </a-layout-header>
  <!-- 修改用户信息弹窗 -->
  <a-modal
    v-model:open="updateModalVisible"
    title="修改个人信息"
    @ok="handleUpdateUser"
    @cancel="closeUpdateModal"
  >
    <a-form :model="updateForm" layout="vertical">
      <a-form-item label="用户名">
        <a-input v-model:value="updateForm.userName" />
      </a-form-item>
      <a-form-item label="用户头像">
        <a-input v-model:value="updateForm.userAvatar" />
      </a-form-item>
      <a-form-item label="简介">
        <a-textarea v-model:value="updateForm.userProfile" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 修改密码弹窗 -->
  <a-modal
    v-model:open="passwordModalVisible"
    title="修改密码"
    @ok="handleUpdatePassword"
    @cancel="closePasswordModal"
  >
    <a-form :model="passwordForm" layout="vertical">
      <a-form-item label="原密码" required>
        <a-input-password v-model:value="passwordForm.oldPassword" />
      </a-form-item>
      <a-form-item label="新密码" required>
        <a-input-password v-model:value="passwordForm.newPassword" />
      </a-form-item>
      <a-form-item label="确认新密码" required>
        <a-input-password v-model:value="passwordForm.confirmPassword" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, h, ref } from 'vue'
import { useRouter } from 'vue-router'
import { type MenuProps, message, Modal } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/loginuser.ts'
import { updatePassword, updateUser, userLogout } from '@/api/userController.ts'
import { HomeOutlined, EditOutlined, LogoutOutlined, LockOutlined } from '@ant-design/icons-vue'


const router = useRouter()
const loginUserStore = useLoginUserStore()
// 当前选中菜单
const selectedKeys = ref<string[]>(['/'])
// 监听路由变化，更新当前选中菜单
router.afterEach((to, from, next) => {
  selectedKeys.value = [to.path]
})

// 菜单配置项
const originItems = [
  {
    key: '/',
    icon: () => h(HomeOutlined),
    label: '主页',
    title: '主页'
  },
  ,
  {
    key: '/admin/userManage',
    label: '用户管理',
    title: '用户管理',
  },
  {
    key: '/admin/appManage',
    label: '应用管理',
    title: '应用管理',
  }
]

// 过滤菜单项
const filterMenus = (menus = [] as MenuProps['items']) => {
  return menus?.filter((menu) => {
    const menuKey = menu?.key as string
    if (menuKey?.startsWith('/admin')) {
      const loginUser = loginUserStore.loginUser
      if (!loginUser || loginUser.userRole !== 'admin') {
        return false
      }
    }
    return true
  })
}

// 展示在菜单的路由数组
const menuItems = computed<MenuProps['items']>(() => filterMenus(originItems))


// 处理菜单点击
const handleMenuClick: MenuProps['onClick'] = (e) => {
  const key = e.key as string
  selectedKeys.value = [key]
  // 跳转到对应页面
  if (key.startsWith('/')) {
    router.push(key)
  }
}
// 用户注销
const doLogout = async () => {
  // 添加确认对话框
  const confirmed = await new Promise<boolean>((resolve) => {
    Modal.confirm({
      title: '确认退出',
      content: '确定要退出登录吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => resolve(true),
      onCancel: () => resolve(false),
    });
  });

  if (!confirmed) {
    return; // 用户取消退出
  }
  const res = await userLogout()
  if (res.data.code === 0) {
    loginUserStore.setLoginUser({
      userName: '未登录'
    })
    message.success('退出登录成功')
    await router.push('/user/login')
  } else {
    message.error('退出登录失败，' + res.data.message)
  }
}

const updateModalVisible = ref(false)
const updateForm = ref({
  userName: '',
  userAvatar: '',
  userProfile: ''
})

const showUpdateModal = () => {
  // 初始化表单数据
  updateForm.value = {
    userName: loginUserStore.loginUser.userName || '',
    userAvatar: loginUserStore.loginUser.userAvatar || '',
    userProfile: loginUserStore.loginUser.userProfile || ''
  }
  updateModalVisible.value = true
}

const closeUpdateModal = () => {
  updateModalVisible.value = false
}

const handleUpdateUser = async () => {
  try {
    // 添加简洁的确认提示
    const confirmed = Modal.confirm({
      title: '确认修改信息？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await updateUser({
            id: loginUserStore.loginUser.id,
            ...updateForm.value
          })

          if (res.data.code === 0) {
            message.success('更新成功')
            // 更新本地存储的用户信息
            loginUserStore.setLoginUser({
              ...loginUserStore.loginUser,
              ...updateForm.value
            })
            closeUpdateModal()
          } else {
            message.error('更新失败: ' + res.data.message)
          }
        } catch (error) {
          message.error('更新失败: ' + error)
        }
      },
    });
  } catch (error) {
    message.error('更新失败: ' + error)
  }
}
// 修改密码相关
const passwordModalVisible = ref(false)

const passwordForm = ref({
  oldPassword:'',
  newPassword: '',
  confirmPassword: ''
})

const showPasswordModal = () => {
  // 重置表单数据
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  passwordModalVisible.value = true
}

const closePasswordModal = () => {
  passwordModalVisible.value = false
}

const handleUpdatePassword = async () => {
  // 表单验证
  if (!passwordForm.value.oldPassword || !passwordForm.value.newPassword || !passwordForm.value.confirmPassword) {
    message.error('请填写所有密码字段')
    return
  }

  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    message.error('新密码与确认密码不一致')
    return
  }

  if (passwordForm.value.newPassword.length < 6) {
    message.error('新密码长度不能少于6位')
    return
  }

  try {
    // 添加确认提示框
    Modal.confirm({
      title: '确认修改密码？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await updatePassword({
            id: loginUserStore.loginUser.id,
            oldPassword: passwordForm.value.oldPassword,
            newPassword: passwordForm.value.newPassword
          })

          if (res.data.code === 0) {
            message.success('密码修改成功')
            closePasswordModal()
            // 可以选择退出登录，要求用户重新登录
            // await doLogout()
          } else {
            message.error('密码修改失败: ' + res.data.message)
          }
        } catch (error) {
          message.error('密码修改失败: ' + error)
        }
      },
    });
  } catch (error) {
    message.error('密码修改失败: ' + error)
  }
}
</script>

<style scoped>
.header {
  background: white; /* 半透明黑色背景 */
  padding: 0 24px;
  backdrop-filter: blur(10px); /* 背景模糊效果 */
  border-bottom: 1px solid rgba(0, 100, 255, 0.3); /* 半透明边框 */
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.3); /* 阴影效果 */
  position: relative;
  overflow: hidden;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
  z-index: 1;
}

.logo {
  height: 48px;
  width: 48px;
  filter: drop-shadow(0 0 8px rgba(0, 150, 255, 0.7));
}

.site-title {
  margin: 0;
  font-size: 18px;
  color: #0f55d6;
  text-shadow: 0 0 10px rgba(248, 245, 245, 0.92);
  font-weight: 600;
  letter-spacing: 1px;
}

.user-login-status {
  display: flex;
  align-items: center;
  height: 100%;
  position: relative;
  z-index: 1;
}

.user-name {
  color: #07021e;
  font-weight: 600;
}

/* 登录按钮科技感样式 */
.login-button {
  background: linear-gradient(90deg, #0066ff, #00ccff);
  border: none;
  box-shadow: 0 0 10px rgba(0, 150, 255, 0.5);
  transition: all 0.3s ease;
  letter-spacing: 1px;
}

.login-button:hover {
  background: linear-gradient(90deg, #00ccff, #0066ff);
  box-shadow: 0 0 15px rgba(0, 200, 255, 0.7);
  transform: translateY(-2px);
}
</style>
